package common

import (
	"bytes"
	"database/sql/driver"
	"fmt"
	"time"
)

type Time struct {
	time.Time `json:"time"`
}

const (
	TimeFormat = "2006-01-02 15:04:05"
)

func (t *Time) UnmarshalJSON(data []byte) (err error) {
	if data == nil || len(string(data)) == 0 {
		return
	}

	data = bytes.Trim(data, "\"")
	tv, err := time.Parse(TimeFormat, string(data))
	*t = Time{tv}

	return err
}

func (t Time) MarshalJSON() ([]byte, error) {
	ts := t.Time.Format(TimeFormat)
	return []byte(fmt.Sprintf("\"%s\"", ts)), nil
}

func (t Time) String() string {
	return t.Time.Format(TimeFormat)
}

func (t Time) Value() (driver.Value, error) {
	// MyTime 转换成 time.Time 类型
	return t.Time.Format("2006-01-02 15:04:05"), nil
}
